home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 1982 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.5 KB  |  50 lines

  1. Path: news.th-darmstadt.de!news!enno
  2. From: enno@inferenzsysteme.informatik.th-darmstadt.de (Enno Sandner)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Returning ref to object - is this code invalid?
  5. Date: 14 Jan 1996 19:43:27 GMT
  6. Organization: Fachbereich Informatik, TH Darmstadt
  7. Distribution: world
  8. Message-ID: <ENNO.96Jan14204327@kitz.inferenzsysteme.informatik.th-darmstadt.de>
  9. References: <30F937D8.12D2@sierra.net>
  10. NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
  11. In-reply-to: TGColwell's message of Sun, 14 Jan 1996 09:05:28 -0800
  12.  
  13. In article <30F937D8.12D2@sierra.net> TGColwell <snowbull@sierra.net> writes:
  14.  
  15.    Does the following code create a dangling reference?
  16.  
  17.    class vector
  18.    { private: float x,y,z;
  19.      public:  //c'tors & functions
  20.    };
  21.  
  22.    class face
  23.    {  private: vector v1, v2, v3;
  24.       public:
  25.        vector& get_vtx_1() const;
  26.    }
  27.  
  28.    vector& face::get_vtx_1() const  //returns reference to vector
  29.    {  return v1;
  30.    }
  31.  
  32.    void main()
  33.    {
  34.      face ff('constructor parameters);
  35.      vector vv = ff.get_vtx_1();
  36.    }
  37.  
  38.    I'm wondering if the return of a reference to v1 will invalidate
  39.    my program since v1 goes out of scope when get_vtx_1() returns, 
  40.    or does v1 stay in scope since ff is not deleted?
  41.  
  42.    Any input is appreciated!
  43.  
  44. 'v1' is a data-member of 'face' so it gets destroyed when the appropriate
  45. 'face' instances goes out of scope. Thus the program doesn't result in a
  46. dangling reference. However 'get_vtx_1' should return a const reference
  47. instead.
  48.  
  49.         Enno
  50.